using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class Recruiters_resumeresult : System.Web.UI.Page
{
    string keyword = "";
     
    string category = "0";
    string industry = "0";
    string province = "0";
    string qualification = "0";
    string type = "0";
    string level = "0";
    string gender = "2";
    string minAge  = "0";
    string maxAge  = "100";

    string available = "0";
    int itemPerPage = 15;
    int pagePerSeggment = 5;
    string postedResume = "0";
    string sortOrder = "JobPosition";
    string connectionString = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["rcuserid"] == null)
                Response.Redirect("login.aspx");
            if (Session["rcactivate"].ToString() == "False")
            {
                btnSaveSearch.Enabled = false;
                btnSearch.Enabled = false;
                litError.Text = "<font color=red><img border=0 src='/icons/warning.gif'>You can not save search scanario, <br>because this account is not approved by management team.</font>";
            }   
            connectionString =
                     WebConfigurationManager.ConnectionStrings[
                       "RecruitVietnam"].ConnectionString;

            RegisterJavaScript(this.GridView1);
            Page searchPage = this.PreviousPage;
            RegisterJavaScript();
            if (searchPage != null)
            {
                switch (searchPage.Title)
                {
                    case "::Search for Resumes":
                        SearchCase(searchPage);
                        break;
                    case "::Saved Resume Searchs":
                        SavedSearchCase(searchPage);
                        break;  
                }
                ShowCV(keyword, qualification, 
                category, industry, province, 
                level, type, gender, 
                minAge, maxAge, 
                available, postedResume, 0);

                this.searchKeyword.Text = keyword;           
                this.hdfIndustry.Value = industry;
                this.hdfProvince.Value = province;
                this.hdfLevel.Value = level;
                
                this.hdfType.Value = type;
                this.hdfGender.Value = gender;
                this.hdfMinAge.Value= minAge;
                this.hdfMaxAge.Value = maxAge;

                hdfAvailable.Value = available;
                showMe.Value = itemPerPage.ToString();
                hdfPostedResume.Value = postedResume;
                hdfSort.Value = sortOrder;

            }

            if (!IsPostBack)
            {
                ViewState["SortDirection"] = "ASC";
                LoadDataForDropDownList();

            }
            else
                CreateNavigation(Convert.ToInt32(
                literalPages.Text), Convert.ToInt32(
                literalCurrentPage.Text), itemPerPage,
                pagePerSeggment, this.panelNavigation);
        }
        catch(Exception ex)
        {
            litError.Text = ex.Message;
        }
    }
    void SavedSearchCase(Page searchPage)
    {
        GridView gridView = (GridView)
        searchPage.FindControl("GridView1");
        GridViewRow gridViewRow =
        gridView.Rows[Convert.ToInt32(
        Request.QueryString.Get("indexRow"))];

        keyword = gridViewRow.Cells[2].Text;
        qualification = gridViewRow.Cells[3].Text;
        category = gridViewRow.Cells[5].Text;        
        industry = gridViewRow.Cells[7].Text;
        province = gridViewRow.Cells[9].Text;
        type = gridViewRow.Cells[11].Text;
        level = gridViewRow.Cells[13].Text;
        available = gridViewRow.Cells[15].Text; 
        gender = gridViewRow.Cells[17].Text;         
        minAge = gridViewRow.Cells[19].Text;
        maxAge = gridViewRow.Cells[20].Text;
                    
        
        postedResume = "0";
        sortOrder = "JobPosition";
    }
    void FillAvailable(GridView GridView1)
    {
        try
        {
            string availableValue;
            foreach (GridViewRow gridViewRow in GridView1.Rows)
            {
                switch(gridViewRow.Cells[5].Text)
                {
                    case "1":
                        availableValue="Within 1 month";
                        break;
                    case "7":
                        availableValue = "After 6 months";
                        break;
                    default:
                        availableValue = 
                        (Convert.ToInt32(gridViewRow.Cells[5].Text)-1).ToString() + "-" 
                        +gridViewRow.Cells[5].Text
                        + " months";
                        break;
                }                 
               gridViewRow.Cells[5].Text= availableValue;
            }
        }
        catch (Exception ex)
        {
            litError.Text = ex.Message;
        }
    }
   void LoadDataForDropDownList()
    {
        Common cls = new Common(connectionString);
         DataSet dataSet = cls.GetDataSet(
        "select * from tblJobCategories; " +
         " select * from tblJSCertificates;");
        DropDownListHelper helper =
        new DropDownListHelper();
        helper.FillDataTableToDropDownList(
        dataSet, new DropDownList[2] { 
        jobCategory, qualificationName},
        new string[2]{"JobCategoryName", 
            "CertificateName"},
        new string[2]{"JobCategoryID", 
           "CertificateID"},
        new string[2] { category, qualification});
    }
    
    void SearchCase(Page searchPage)
    {
        TextBox textBox;
        DropDownList dropDownList;
        textBox = (TextBox)
        searchPage.FindControl("searchKeyword");
        keyword = textBox.Text;
        
        dropDownList = (DropDownList)
        searchPage.FindControl("qualificationName");
        qualification = dropDownList.SelectedValue;
        
        dropDownList = (DropDownList)
        searchPage.FindControl("jobCategory");
        category = dropDownList.SelectedValue;
        
        dropDownList = (DropDownList)
        searchPage.FindControl("jobIndustry");
        industry = dropDownList.SelectedValue;
        
        dropDownList = (DropDownList)
        searchPage.FindControl("provinceName");
        province = dropDownList.SelectedValue;

        dropDownList = (DropDownList)
                searchPage.FindControl("workingLevel");
        level = dropDownList.SelectedValue;

        dropDownList = (DropDownList)
        searchPage.FindControl("workingType");
        type = dropDownList.SelectedValue;       

        dropDownList = (DropDownList)
        searchPage.FindControl("genderName");
        gender = dropDownList.SelectedValue;

        textBox = (TextBox)
                searchPage.FindControl("minAge");
        minAge = textBox.Text;
        if(minAge =="") minAge ="0";
        
        textBox = (TextBox)
                searchPage.FindControl("maxAge");
        maxAge = textBox.Text;
        if (maxAge == "") maxAge = "100";
        
        dropDownList = (DropDownList)
        searchPage.FindControl("availableResume");
        available = dropDownList.SelectedValue;
        
        dropDownList = (DropDownList)
        searchPage.FindControl("showMe");
        itemPerPage = Convert.ToInt32(
        dropDownList.SelectedValue);
        dropDownList = (DropDownList)
        searchPage.FindControl("resumePosted");
        postedResume = dropDownList.SelectedValue;
        dropDownList = (DropDownList)
        searchPage.FindControl("resumeSort");
        sortOrder = dropDownList.SelectedValue;
    }

    DataTable GetDataTable(string keyword,
    string qualification, string category,
    string industry, string province,
    string level, string type, string gender, 
    string min, string max,
    string available, string resumeNoOfDate,
    int firstRecord)
    {
        SqlServerProvider sqlServerProvider =
        new SqlServerProvider();
        sqlServerProvider.ConnectionString =
        connectionString;
        sqlServerProvider.ParameterCollection
        = new string[14] 
            {"@Keyword", "@Category", "@Industry", 
            "@Province", "@Qualification",
            "@Level", "@Type", "@Gender",
            "@MinAge", "@MaxAge",
            "@Available", "@ResumeNoOfDate", 
            "@Total", "@RecruiterID"};
        sqlServerProvider.ValueCollection =
        new string[14] 
            { "%" + keyword + "%", category, 
            industry, province, qualification,
            level, type, gender, min, max, 
            available, resumeNoOfDate, "1",
            Session["rcuserid"].ToString()};
        sqlServerProvider.CommandType =
        CommandType.StoredProcedure;
        sqlServerProvider.CommandText =
                    "SPSearchResume";
        if (firstRecord == 0)
        {
            
            literalTotal.Text =
            sqlServerProvider.ExecuteScalar().ToString();
            ShowTotalPages(Convert.ToInt32(
            literalTotal.Text));
        }
        sqlServerProvider.ValueCollection[12] = "0";         
        DataTable dataTable =
        sqlServerProvider.GetDataTable(
        firstRecord * itemPerPage, itemPerPage);
        return dataTable;
    }
    DataView GetDataView(string keyword,
        string qualification, string category,
        string industry, string province,
        string level, string type, string gender,
        string min, string max,
        string available, string resumeNoOfDate,
        string columnName, string sortType, int firstRecord)
    {
        SqlServerProvider sqlServerProvider =
        new SqlServerProvider();
        sqlServerProvider.ConnectionString =
        connectionString;
        sqlServerProvider.ParameterCollection
        = new string[14] 
            {"@Keyword", "@Category", "@Industry", 
            "@Province", "@Qualification",
            "@Level", "@Type", "@Gender",
            "@MinAge", "@MaxAge",
            "@Available", "@ResumeNoOfDate", 
            "@Total", "@RecruiterID"};
        sqlServerProvider.ValueCollection =
        new string[14] 
            { "%" + keyword + "%", category, 
            industry, province, qualification,
            level, type, gender, min, max, 
            available, resumeNoOfDate, "0",
            Session["rcuserid"].ToString()};
        sqlServerProvider.CommandType =
        CommandType.StoredProcedure;

        sqlServerProvider.CommandText =
         "SPSearchResume";
        DataTable dataTable =
        sqlServerProvider.GetDataTable(
        firstRecord * itemPerPage, itemPerPage);
        DataView dataView = new DataView(dataTable);
        dataView.Sort = columnName + " " + sortType;
        return dataView;
    }
    void ShowTotalPages(int totalRecords)
    {

        int totalPages = totalRecords / itemPerPage;
        if (totalRecords % itemPerPage != 0)
            totalPages++;
        literalPages.Text = totalPages.ToString();
    }

    void CreateNavigation(
    int totalPages,
    int currentPage,
    int itemPerPage,
    int pagePerSeggent,
    Panel panelLinks)
    {
        panelLinks.Controls.Clear();
        int startPageNo = 0;
        int endPageNo = 0;
        int seggmentNo = 0;
        if (totalPages > 1)
        {
            seggmentNo =
            currentPage / pagePerSeggent;
            if ((currentPage % pagePerSeggent) > 0)
                seggmentNo += 1;
            startPageNo =
            pagePerSeggent * (seggmentNo - 1) + 1;
            if (seggmentNo * pagePerSeggent > totalPages)
                endPageNo = totalPages;
            else
                endPageNo = seggmentNo * pagePerSeggent;


            LinkButton linkButton;
            Label labelSpace;

            if (seggmentNo > 1)
            {
                linkButton = new LinkButton();
                linkButton.Text = "First";
                linkButton.Click += new
                EventHandler(linkButton_Click);
                linkButton.ID = (1).ToString();
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }

            if (currentPage > pagePerSeggent)
            {
                linkButton = new LinkButton();
                linkButton.Text = "Previous";
                linkButton.Click += new
                EventHandler(linkButton_Click);
                linkButton.ID = (startPageNo - 1).ToString();
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            int i = 0;
            for (i = startPageNo; i <= endPageNo; i++)
            {
                linkButton = new LinkButton();
                linkButton.Text = i.ToString();

                linkButton.ID = i.ToString();
                if (i == currentPage)
                    linkButton.BackColor =
                    System.Drawing.Color.Aqua;
                linkButton.Click += new
                EventHandler(linkButton_Click);
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            if (seggmentNo * pagePerSeggent < totalPages)
            {
                linkButton = new LinkButton();
                linkButton.Text = "Next";
                linkButton.ID = (i).ToString();
                linkButton.Click += new
                EventHandler(linkButton_Click);
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            if (seggmentNo * pagePerSeggent + 1 < totalPages)
            {
                linkButton = new LinkButton();
                linkButton.Text = "Last";
                linkButton.ID = totalPages.ToString();
                linkButton.Click += new
                EventHandler(linkButton_Click);
                labelSpace = new Label();
                labelSpace.Text = "&nbsp;";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
        }
    }

    void linkButton_Click(object sender, EventArgs e)
    {
 
        keyword = searchKeyword.Text;         
        category = this.jobCategory.SelectedValue;
        qualification = this.qualificationName.SelectedValue;
        industry = this.hdfIndustry.Value;
        province = this.hdfProvince.Value;
        type = this.hdfType.Value;
        level = this.hdfLevel.Value;
        gender = this.hdfGender.Value;
        minAge = this.hdfMinAge.Value;
        maxAge = this.hdfMaxAge.Value;
        available = hdfAvailable.Value;
        itemPerPage =
        Convert.ToInt32(showMe.Value);
        postedResume = hdfPostedResume.Value;
        sortOrder = hdfSort.Value;

        LinkButton linkButton =
        (LinkButton)sender;

        int nextPage = 0;
        nextPage = Convert.ToInt32(linkButton.ID);
        literalCurrentPage.Text =
        nextPage.ToString();
        int endJobs =
        nextPage * Convert.ToInt32(itemPerPage);
        if (endJobs > Convert.ToInt32(literalTotal.Text))
            endJobs = Convert.ToInt32(literalTotal.Text);
        literalRecords.Text =
        " - Display job: " +
        (nextPage - 1) * itemPerPage +
        " -> " + endJobs.ToString();

        ShowCV(keyword, qualification, 
            category, industry, province, 
            level, type, gender, 
            minAge, maxAge, 
            available, postedResume,
            nextPage - 1);

   
    }
     
    void ShowCV(string keyword,
    string qualification, string category,
    string industry, string province,
    string level, 
    string type, string gender, 
    string min, string max,
    string available, string resumeNoOfDate,
    int firstRecord)
    {
        try
        {

            GridViewHelper gridViewHelper =
            new GridViewHelper();
            gridViewHelper.FillDataTableToGridView(
            GetDataTable(keyword, qualification,
            category, industry, province,
            level, type, gender, min, max,
            available, resumeNoOfDate, firstRecord),
            this.GridView1);
            if (GridView1.Rows.Count == 0)
            {
                litError.Text = "Resume not found.";
                ShowHide(false);
            }
            else
            {
                ShowHide(true);
                FillAvailable(GridView1);
                int currentRecords =
                Convert.ToInt32(literalCurrentPage.Text);
                litError.Text = "";
                literalRecords.Text =
                " - Display job: " +
                ((currentRecords - 1) * itemPerPage + 1).ToString()
                + "-";
                if ((currentRecords - 1) * itemPerPage +
                itemPerPage < Convert.ToInt32(literalTotal.Text))
                    literalRecords.Text +=
                    ((currentRecords - 1) * itemPerPage +
                    itemPerPage).ToString();
                else
                    literalRecords.Text += literalTotal.Text;
                literalRecords.Text += " of " +
                literalTotal.Text;
            }
            CreateNavigation(Convert.ToInt32(
                         literalPages.Text), Convert.ToInt32(
                         literalCurrentPage.Text), itemPerPage,
                         pagePerSeggment, this.panelNavigation);
        }
        catch (Exception ex)
        {
            litError.Text = ex.Message;
        }
    }
    
    void ShowResult(string keyword,
    string qualification, string category,
    string industry, string province,
    string level,
    string type, string gender,
    string min, string max,
    string available, string resumeNoOfDate, 
    string columnName, string sortType,
    int firstRecord)
    {
        try
        {

            GridViewHelper gridViewHelper =
            new GridViewHelper();
            gridViewHelper.FillDataViewToGridView(
            GetDataView(keyword, qualification,
            category, industry, province,
            level, type, gender, min, max,
            available, resumeNoOfDate, 
            columnName, sortType, firstRecord),
            this.GridView1);
            if (GridView1.Rows.Count == 0)
                litError.Text = "Resume not found.";                 
            else
            {
                litError.Text = "";
                FillAvailable(GridView1);
            }
        }
        catch (Exception ex)
        {
            litError.Text = ex.Message;
        }
    }
    void ShowHide(bool flag)
    {
        literalTotal.Visible = flag;
        literalCurrentPage.Visible = flag;
        literalOfText.Visible = flag;
        literalPageText.Visible = flag;
        literalTotalText.Visible = flag;
        literalRecords.Visible = flag;
        literalPages.Visible = flag;
        btnSaveSearch.Visible = flag;
        btnPrint.Visible = flag;
    }
     
    void RegisterJavaScript()
    {
        string javaScript =
        "<script langugage=javascript> " +
        "function NewSearch(){";
        javaScript += "window.open(\"" +
        " search.aspx\", target='_main');} " +
        "</script>";
        ClientScript.RegisterClientScriptBlock(
        this.GetType(), "JobResult", javaScript);
    }

    void RegisterJavaScript(GridView GridView1)
    {
        Common common = new Common();
        ClientScript.RegisterClientScriptBlock(
        this.GetType(), "openWindow" +
        GridView1.ID,
        common.CreateScriptForPrint(
        GridView1.ID));
        btnPrint.Attributes.Add("onclick",
        "openWindow" + GridView1.ID +
        "('" + GridView1.ID.ToString() +
        "',400,700);return false;");
    }

    protected void btnSearch_Click(
    object sender, EventArgs e)
    {
        keyword = searchKeyword.Text;         
        category = this.jobCategory.SelectedValue;
        qualification = this.qualificationName.SelectedValue;
        industry = this.hdfIndustry.Value;
        province = this.hdfProvince.Value;
        type = this.hdfType.Value;
        level = this.hdfLevel.Value;
        gender = this.hdfGender.Value;
        minAge = this.hdfMinAge.Value;
        maxAge = this.hdfMaxAge.Value;
        available = hdfAvailable.Value;
        itemPerPage =
        Convert.ToInt32(showMe.Value);
        postedResume = hdfPostedResume.Value;
        sortOrder = hdfSort.Value;

        literalCurrentPage.Text = "1";
        

        ShowCV(keyword, qualification,
            category, industry, province,
            level, type, gender,
            minAge, maxAge,
            available, postedResume, 0);

 
    }
    protected void btnSaveJobSearch_Click(
    object sender, EventArgs e)
    {
        if (Convert.ToString(
                Session["rcuserid"]) == "")
            Response.Redirect("login.aspx");

        RecruitVietnam cls = new RecruitVietnam();
        cls.ConnectionString = connectionString;
        if(!cls.SaveResumeSearch(
        Session["rcuserid"].ToString(),
        searchKeyword.Text,
        qualificationName.SelectedValue,
        jobCategory.SelectedValue,
        this.hdfIndustry.Value,
        hdfProvince.Value,
        this.hdfLevel.Value,
        this.hdfType.Value,
        this.hdfGender.Value,
        hdfAvailable.Value,
        hdfMinAge.Value, hdfMaxAge.Value))
        litError.Text = cls.ErrorMessage;
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {

        keyword = searchKeyword.Text;
        category = this.jobCategory.SelectedValue;
        qualification = this.qualificationName.SelectedValue;
        industry = this.hdfIndustry.Value;
        province = this.hdfProvince.Value;
        type = this.hdfType.Value;
        level = this.hdfLevel.Value;
        gender = this.hdfGender.Value;
        minAge = this.hdfMinAge.Value;
        maxAge = this.hdfMaxAge.Value;
        available = hdfAvailable.Value;
        itemPerPage =
        Convert.ToInt32(showMe.Value);
        postedResume = hdfPostedResume.Value;
        sortOrder = hdfSort.Value;

        ShowResult(keyword, qualification,
            category, industry, province,
            level, type, gender,
            minAge, maxAge,
            available, postedResume,
        e.SortExpression,
        ViewState["SortDirection"].ToString(),
        Convert.ToInt32(literalCurrentPage.Text) - 1);

        if (ViewState["SortDirection"].ToString() == "ASC")
            ViewState["SortDirection"] = "DESC";
        else
            ViewState["SortDirection"] = "ASC";

    }
}
